<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/15/015
 * Time: 10:48
 */

namespace app\api\controller;


use app\common\controller\Api;

class Useraddress extends Api
{
    protected $noNeedLogin = ['*'];

    public function index()
    {
        $user_id = $this->request->request('user_id');
        if (!\app\common\model\User::get($user_id)) {
            $this->error('没有这个用户');
        }
        $model = new \app\api\model\Useraddress();
        $result = $model->where('user_id',$user_id)->select();
        if(!$result){
            $this->error('该用户没有设置地址');
        }
        $this->success('',$result);
    }
    public function add()
    {
        $user_id = $this->request->request('user_id');
        if (!\app\common\model\User::get($user_id)) {
            $this->error('没有这个用户');
        }
        $model = new \app\api\model\Useraddress();
        $result = $model->allowField(true)->validate(true)->save($_POST);
        if ($result) {
            $this->success('成功');
        }
        $this->error($model->getError());
    }

    public function edit()
    {
        $id = $this->request->request('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $user_id = $this->request->request('user_id');
        if (!\app\common\model\User::get($user_id)) {
            $this->error('没有这个用户');
        }

        if (!\app\api\model\Useraddress::get($id)) {
            $this->error('没有这个地址');
        }
        $model = new \app\api\model\Useraddress();
        $result = $model->allowField(true)->validate(true)->save($_POST, ['id' => $id]);
        if ($result) {
            $this->success('成功');
        }
        $this->error($model->getError());

    }

    /**
     * 判断删除是否有权限删除
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $id = $this->request->request('id');
        if(!$id){
            $this->error(__('Invalid parameters'));
        }
        $model = \app\api\model\Useraddress::get($id);
        if(!$model){
            $this->error('找不到这条数据');
        }
        $result =$model->delete();
        if ($result) {
            $this->success('成功');
        }
        $this->error($model->getError());
    }

}